<?php

namespace App\Admin\Controllers;

use App\Models\AdminUser;
use App\Models\Material;
use App\Models\Purchase;
use App\Models\RecordMaterial;
use App\Models\Supplier;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Auth;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Arr;
use App\Admin\Handles;

class PurchaseController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '采购';

    protected $payType = [1 => '现金', 2 => '银行卡', 3 => '微信', 4 => '支付宝', 5 => '赊账'];

    protected $status = [1 => '申请', 2 => '通过', 3 => '拒绝'];

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Purchase());

        $grid->column('handler', '经手人')
            ->using(AdminUser::All()->pluck('name', 'id')->toArray());
        $grid->column('total_price', '合计')->display(function($data){
            return $data = '￥'.$data;
        })->sortable();
        $grid->column('other_price', '其他')->display(function($data){
            return $data = '￥'.$data;
        })->sortable();
        $grid->column('price', '实际价格')->display(function($data){
            return $data = '￥'.$data;
        })->sortable();
        $grid->column('pay_type', '支付状态')
            ->using($this->payType)->dot([
                1 => 'info',
                2 => 'success',
                3 => 'warning',
                4 => 'danger',
                5 => 'primary'
            ]);
        $grid->column('status', __('Status'))
            ->using($this->status)->dot([1 => 'info', 2 => 'success', 3 => 'danger']);
        $grid->column('created_at', __('Created at'))->sortable();
        $grid->column('updated_at', __('Updated at'))->sortable();

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
        });
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();

            $filter->equal('handler', '经手人')
            ->select(AdminUser::where('store_id', Admin::user()->store_id)->pluck('name', 'id'));
            $filter->equal('pay_type', '支付状态')
                ->radio(Arr::add($this->payType, '', '全部'));
            $filter->equal('status', __('Status'))
                ->radio(Arr::add($this->status, '', '全部'));
            $filter->between('created_at', '时间')->datetime();
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Purchase::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('number', __('Number'));
        $show->field('description', __('Description'));
        $show->field('handler', __('Handler'));
        $show->field('time', __('Time'));
        $show->field('total_price', __('Total price'));
        $show->field('other_price', __('Other price'));
        $show->field('price', __('Price'));
        $show->field('pay_type', __('Pay type'));
        $show->field('status', __('Status'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));
        $show->field('deleted_at', __('Deleted at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $admin = Auth::guard('admin')->user();

        $form = new Form(new Purchase());

        $form->select('handler', '经手人')
            ->options(AdminUser::where('store_id', Admin::user()->store_id)->pluck('name', 'id'))
            ->rules('required');
		$form->hidden('store_id');
        $form->hasMany('purchasetomaterial', '材料', function (Form\NestedForm $form) {
            $form->select('material_id', '材料')
                ->options(Material::All()->pluck('name', 'id'));
            $form->select('supplier_id', '供应商')
                ->options(Supplier::All()->pluck('company', 'id'));
            $form->number('number', '数量');
            $form->currency('unit_price', '单位价格')->symbol('￥');
        });

        $form->hidden('total_price', __('Total price'));

        $form->currency('other_price', '其他费用')
            ->symbol('￥');

        $form->currency('price', '实际支付费用')->symbol('￥');

        $form->textarea('description', __('Description'));

        $form->select('pay_type', '支付方式')
            ->options([1 => '现金', 2 => '银行卡', 3 => '微信', 4 => '支付宝', 5 => '赊账'])
            ->default(1)
            ->rules('required');
		if(Route::currentRouteName() === 'purchases.create') {
			$form->select('status', __('Status'))
	            ->options([1 => '申请'])->default(1)
	            ->rules('required');
		} else {
			$form->select('status', __('Status'))
	            ->options([1 => '申请', 2 => '通过', 3 => '拒绝'])->default(1)->disable();
		}
		
        $form->hidden('number');
        $form->hidden('time');

        $form->saving(function (Form $form) {
            // 生成采购单号，采购时间戳
            $form->number = 'CGDD'.time().$form->pay_type.$form->status;
            $form->time = time();
			$form->store_id = Admin::user()->store_id;
            // 计算合计费用 = 材料单价 * 数量
            $form->total_price = sumMaterialPurchasePrice($form->purchasetomaterial);
            $form->price = $form->total_price + $form->other_price;
            
        });

        $form->saved(function (Form $form) {
            // 生成采购历史记录
            $purchase = Purchase::find($form->model()->id);
            $param = $purchase->purchasetomaterial;
            // 采购同意时再生成 先注释
            // foreach ($param as $k => $v) {
            //     $data = [
            //         'purchase_to_material_id' => $v->id,
            //         'material_id' => $v->material_id,
            //         'number' => $v->number,
            //         'description' => $v->description,
            //         'style' => 1,
            //         'type' => 1
            //     ];
            //     $recordMaterial = RecordMaterial::create($data);
            // }
            foreach ($form->model()->purchasetomaterial as $k => $v) {
                $form->model()->purchasetomaterial[$k]['stock'] = $v['number'];
                $form->model()->purchasetomaterial[$k]['status'] = 1;
            }
            $form->model()->push();
        });

        // 编辑时不显示提交按钮
        if (Route::currentRouteName() == 'purchases.edit') {
            $form->footer(function ($footer){
                $footer->disableSubmit();
                $footer->disableReset();
            });
        } else {
            $form->footer(function ($footer) {
                $footer->disableEditingCheck();
            });
        }

        return $form;
    }
}
